﻿<%@ WebHandler Language="C#" Class="RbPhysicoChemicalCheckHandler" %>
/*Description: 热表理化检测管理
'Copyright (c) : 通力凯顿（北京）系统集成有限公司
'Writer: Zhangrj 
'create Date:20250417
'Rewriter:
'Rewrite Date:
*/
using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Text;
using System.Linq;
using System.IO;
using Newtonsoft.Json;
using System.Collections.Generic;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using System.Collections;
using NPOI.SS.UserModel;
using Camstar.WebClient.WebServicesProxy.InSiteWebServices;
using BusinessRule.Common;

public class RbPhysicoChemicalCheckHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    private uLMSCommonBusiness m_CommonObj = new uLMSCommonBusiness();
    string toAppId = System.Configuration.ConfigurationManager.AppSettings["ToAppID_RB"].ToString();////数据中心推送目的ID（热表）
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            string action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            if (m_UserInfo == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "登录过期，请重新登录" }));
                return;
            }
            switch (action)
            {
                case "GetPhysicoChemicalCheckPageData": //获取理化申请页面初始化的数据
                    GetPhysicoChemicalCheckPageData(context);
                    break;
                case "GetPhysicoChemicalCheckList": //获取热表理化检测列表
                    GetPhysicoChemicalCheckList(context);
                    break;
                case "GetSpecInfoByProductId": //通过件号ID获取工序列表
                    GetSpecInfoByProductId(context);
                    break;
                case "SavePhysicoChemicalCheck": //保存理化申请数据
                    SavePhysicoChemicalCheck(context);
                    break;
                default:
                    context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "不存在该功能" }));
                    break;
            }
        }
        catch (Exception ex)
        {
            uMESProcessResult result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    /// <summary>
    /// 获取理化申请页面初始化的数据
    /// </summary>
    /// <param name="context"></param>
    private void GetPhysicoChemicalCheckList(HttpContext context)
    {
        StringBuilder sql = new StringBuilder();
        Dictionary<string, string> dicParam = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["paramDatas"].ToString());
        sql.AppendLine(@"SELECT r.productid,r.productname,r.workflowstepname,r.checkitemname,r.checkstandard,r.Rbphysicochemicalcheckinfoid checkid,
                         r.Createtime,r.updatetime,e.fullname createempname,ee.fullname updateempname
                         FROM RbPhysicoChemicalCheckInfo r 
                         LEFT JOIN employee e ON e.employeeid = r.createby
                         LEFT JOIN employee ee ON ee.employeeid = r.updateby
                         WHERE r.status = 0");
        if (!string.IsNullOrWhiteSpace(dicParam["checkItemName"])) //检测项目
        {
            sql.AppendFormat(" AND r.checkitemname = '{0}'", dicParam["checkItemName"]);
        }
        if (!string.IsNullOrWhiteSpace(dicParam["productName"])) //件号
        {
            sql.AppendFormat(" AND r.productName LIKE '%{0}%'", dicParam["productName"]);
        }
        if (!string.IsNullOrWhiteSpace(dicParam["specNo"])) //工序
        {
            sql.AppendFormat(" AND r.workflowstepname LIKE '%{0}%'", dicParam["specNo"]);
        }
        sql.AppendLine(" ORDER BY r.createtime DESC, r.productname");
        uMESPagingDataDTO pageDto = new uMESPagingDataDTO();
        pageDto.CurrentPageIndex = int.Parse(dicParam["pageIndex"].ToString());
        pageDto.PageSize = int.Parse(dicParam["pageSize"].ToString());
        pageDto.strSQL = sql.ToString();
        uMESProcessResult result = DatabaseHelper.RunProcedureForPage(pageDto);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取理化申请页面数据
    /// </summary>
    /// <param name="context"></param>
    private void GetPhysicoChemicalCheckPageData(HttpContext context)
    {
        string querySql = @"SELECT ci.customobjectitemsid itemid,ci.customobjectitemsname itemname FROM CustomObject C
                            LEFT JOIN customobjectitems ci ON ci.customobjectid = c.customobjectid AND ci.isuse = 0
                            WHERE c.customobjectname = '热表理化申请检测项目' AND c.isuse = 0";
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        result.DBTable = DatabaseHelper.Query_ReturnDatTable(querySql);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 保存理化申请数据并推送到工控网
    /// </summary>
    /// <param name="context"></param>
    private void SavePhysicoChemicalCheck(HttpContext context)
    {
        ArrayList sqlList = new ArrayList();
        uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "保存成功" };
        StringBuilder sqlBd = new StringBuilder();
        Dictionary<string, string> dicParam = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["paramDatas"].ToString());
        if (string.IsNullOrWhiteSpace(dicParam["productName"]) || string.IsNullOrWhiteSpace(dicParam["workflowStepName"])
            || string.IsNullOrWhiteSpace(dicParam["checkItemName"]) || string.IsNullOrWhiteSpace(dicParam["checkStandard"]))
        {
            result.Result = false; result.Message = "必填项不能为空！";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        dicParam["productName"] = dicParam["productName"].Split(':')[0];//去掉后面的版本和说明
        if (string.IsNullOrWhiteSpace(dicParam["physicoChemicalCheckId"]))//如果ID为空，则添加
        {
            string querySql = @"SELECT 1 FROM RbPhysicoChemicalCheckInfo r WHERE r.productname = '{0}' AND r.workflowstepname = '{1}' 
                                AND r.checkitemname = '{2}' AND r.status = 0";
            querySql = string.Format(querySql, dicParam["productName"], dicParam["workflowStepName"], dicParam["checkItemName"]);
            if (DatabaseHelper.GetSingle(querySql) != null)
            {
                result.Result = false; result.Message = "已存在相同件号、工序、检测项目的数据，无法继续添加！";
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }
            string checkId = Guid.NewGuid().ToString();
            sqlBd.AppendLine(@"INSERT INTO RbPhysicoChemicalCheckInfo(Rbphysicochemicalcheckinfoid,Productid,Productname,Workflowstepid,Workflowstepname,
                               Checkitemname,Checkstandard,Createtime,Createby,Status) VALUES(");
            sqlBd.AppendFormat("'{0}',", checkId);//主键ID
            sqlBd.AppendFormat("'{0}',", dicParam["productID"]);//件号ID
            sqlBd.AppendFormat("'{0}',", dicParam["productName"]);//件号
            sqlBd.AppendFormat("'{0}',", dicParam["workflowStepID"]);//工序ID
            sqlBd.AppendFormat("'{0}',", dicParam["workflowStepName"]);//工序名
            sqlBd.AppendFormat("'{0}',", dicParam["checkItemName"]);//检测项目
            sqlBd.AppendFormat("'{0}',", dicParam["checkStandard"]);//检测标准
            sqlBd.AppendLine("sysdate,");//创建时间
            sqlBd.AppendFormat("'{0}',", m_UserInfo.EmployeeID);//创建人
            sqlBd.AppendLine("0)");//默认有效
            sqlList.Add(sqlBd.ToString());
            /*将新增的数据插入推送记录表*/
            DataTable dtSync = new DataTable();
            dtSync.Columns.Add("Rbphysicochemicalcheckinfoid");
            dtSync.Rows.Add(checkId);
            sqlList.AddRange(m_CommonObj.InsertSyncTableChangeRecode(dtSync, "RbPhysicoChemicalCheckInfo", "Rbphysicochemicalcheckinfoid", toAppId, 1, false));
        }
        else
        {
            sqlBd.AppendLine(@"UPDATE RbPhysicoChemicalCheckInfo r SET ");
            sqlBd.AppendFormat("r.productid = '{0}',", dicParam["productID"]);//件号ID
            sqlBd.AppendFormat("r.productname = '{0}',", dicParam["productName"]);//件号
            sqlBd.AppendFormat("r.workflowstepid = '{0}',", dicParam["workflowStepID"]);//工序ID
            sqlBd.AppendFormat("r.workflowstepname = '{0}',", dicParam["workflowStepName"]);//工序名
            sqlBd.AppendFormat("r.checkitemname = '{0}',", dicParam["checkItemName"]);//检测项目
            sqlBd.AppendFormat("r.checkstandard = '{0}',", dicParam["checkStandard"]);//检测标准
            sqlBd.AppendLine("r.updatetime = sysdate,");//修改时间
            sqlBd.AppendFormat("r.updateby = '{0}'", m_UserInfo.EmployeeID);//修改人
            sqlBd.AppendFormat(" WHERE r.rbphysicochemicalcheckinfoid = '{0}'", dicParam["physicoChemicalCheckId"]);//主键ID
            sqlList.Add(sqlBd.ToString());
            /*将更新的数据插入推送记录表*/
            DataTable dtSync = new DataTable();
            dtSync.Columns.Add("Rbphysicochemicalcheckinfoid");
            dtSync.Rows.Add(dicParam["physicoChemicalCheckId"]);
            sqlList.AddRange(m_CommonObj.InsertSyncTableChangeRecode(dtSync, "RbPhysicoChemicalCheckInfo", "Rbphysicochemicalcheckinfoid", toAppId, 2, false));
        }
        DatabaseHelper.ExecuteSqlTran(sqlList);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 通过件号ID获取工序列表
    /// </summary>
    /// <param name="context"></param>
    private void GetSpecInfoByProductId(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        string sql = string.Format(@"SELECT ws.workflowstepid,ws.workflowstepname FROM PRODUCT p
                        LEFT JOIN Workflowbase wb ON wb.workflowbaseid = p.workflowbaseid
                        LEFT JOIN workflow w ON w.workflowid = NVL(wb.revofrcdid,p.workflowid)
                        LEFT JOIN workflowstep ws ON ws.workflowid = w.workflowid
                        WHERE p.productid = '{0}'
                        ORDER BY ws.sequence", context.Request["productId"].ToString());
        result.DBTable = DatabaseHelper.Query_ReturnDatTable(sql);
        if (result.DBTable.Rows.Count == 0)
        {
            result.Message = "该件号下没有工序！"; result.Result = false;
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}